use actix_web::{dev::{Service, ServiceRequest, ServiceResponse, Transform}, error, error::Error as ActixError, Error};
use futures::future::{ok, Ready, LocalBoxFuture};
use std::rc::Rc;
use std::task::{Context, Poll};

// 定义 AuthenticationMiddleware
pub struct AuthenticationMiddleware;

impl<S, B> Transform<S, ServiceRequest> for AuthenticationMiddleware
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = Error;
    type InitError = ();
    type Transform = AuthenticationMiddlewareService<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ok(AuthenticationMiddlewareService {
            service: Rc::new(service),
        })
    }
}

pub struct AuthenticationMiddlewareService<S> {
    service: Rc<S>,
}

impl<S, B> Service<ServiceRequest> for AuthenticationMiddlewareService<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = Error;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.service.poll_ready(cx)
    }

    fn call(&self, req: ServiceRequest) -> Self::Future {
        let path = req.path();
        log::info!("{} {}", path, req.method());

        // 检查 Authorization 请求头
        let auth_header = req.headers().get("Authorization").and_then(|header| header.to_str().ok());



        if let Some(auth) = auth_header {
            if validate_token(auth) {
                // Token 验证成功，继续处理请求
                let fut = self.service.call(req);
                Box::pin(async move { fut.await })
            } else {
                // Token 验证失败，返回错误响应
                // let response = HttpResponse::Unauthorized().body("Invalid Authorization Token");
                // let (request, _pl) = req.into_parts();
                // 使用 ServiceResponse::from_err 方法返回错误响应
                // let service_response = ServiceResponse::new(
                //     request,response
                // );
                // return Box::pin(async { Ok(ServiceResponse::new(request, response)) });

                Box::pin(async move {
                    Err(error::ErrorUnauthorized("Invalid Authorization Token"))
                })
            }
        } else {
            // Authorization 头缺失，返回错误响应
            // let response = HttpResponse::Unauthorized().body("Authorization Header Not Found");
            // let (request, _pl) = req.into_parts();
            // 使用 ServiceResponse::from_err 方法返回错误响应
            // return Box::pin(async { Ok(ServiceResponse::new(request, response)) });
            Box::pin(async move {

                Err(error::ErrorUnauthorized("Authorization Header Not Found"))
            })
        }
    }
}

// 简单的验证函数，仅用于示例
fn validate_token(token: &str) -> bool {
    println!("Validating {}", token);
    // token == "123"; // 简单的令牌验证逻辑
    true
}
